using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

using Appetite.Domain.Models;
using Appetite.Domain.Repository;

namespace Appetite.Data.EntityFramework.Repository
{
    // TODO : Strip this scaffolded repository. Still nog sure why on earth we want to scaffold all these things ...
    public class RecipeRepository : IRecipeRepository
    {
        AppetiteDomainContext context = new AppetiteDomainContext();

        public IQueryable<Recipe> All
        {
            get { return context.Recipes; }
        }

        public IQueryable<Recipe> AllIncluding(params Expression<Func<Recipe, object>>[] includeProperties)
        {
            IQueryable<Recipe> query = context.Recipes;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Recipe Find(System.Guid id)
        {
            return context.Recipes.Find(id);
        }

        public void InsertOrUpdate(Recipe recipe)
        {
            if (recipe.Id == default(System.Guid))
            {
                recipe.Id = GuidHelper.NewSequentialGuid();
                context.Recipes.Add(recipe);
            }
            else
            {
                recipe.ModificationDate = DateTime.Now;
                context.Entry(recipe).State = EntityState.Modified;
            }
        }

        public void Delete(System.Guid id)
        {
            var recipe = context.Recipes.Find(id);
            context.Recipes.Remove(recipe);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }
}